package com.smart.campus.web.controller.school;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.smart.campus.framework.util.ShiroUtils;
import com.smart.campus.framework.web.service.DictService;
import com.smart.campus.school.domain.ExamAnswer;
import com.smart.campus.school.domain.PsychologicalTest;
import com.smart.campus.school.domain.PsychologicalTestItem;
import com.smart.campus.system.utils.DictUtils;
import com.smart.campus.web.utils.PdfUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.iherus.codegen.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smart.campus.common.annotation.Log;
import com.smart.campus.common.enums.BusinessType;
import com.smart.campus.school.domain.ExamPaper;
import com.smart.campus.school.service.IExamPaperService;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.poi.ExcelUtil;
import com.smart.campus.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.smart.campus.web.utils.PdfUtil.createPdf;

/**
 * 试卷Controller
 * 
 * @author Zhihe.Li
 * @date 2020-05-20
 */
@Controller
@RequestMapping("/school/paper")
public class ExamPaperController extends BaseController
{
    private String prefix = "school/paper";

    @Autowired
    private IExamPaperService examPaperService;

    @Autowired
    private DictService dictService;

    @RequiresPermissions("school:paper:view")
    @GetMapping()
    public String paper()
    {
        return prefix + "/paper";
    }

    /**
     * 查询试卷列表
     */
    @RequiresPermissions("school:paper:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ExamPaper examPaper)
    {
        startPage();
        List<ExamPaper> list = examPaperService.selectExamPaperList(examPaper);
        return getDataTable(list);
    }

    /**
     * 导出试卷列表
     */
    @RequiresPermissions("school:paper:export")
    @Log(title = "试卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ExamPaper examPaper)
    {
        List<ExamPaper> list = examPaperService.selectExamPaperList(examPaper);
        ExcelUtil<ExamPaper> util = new ExcelUtil<ExamPaper>(ExamPaper.class);
        return util.exportExcel(list, "paper");
    }

    /**
     * 新增试卷
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存试卷
     */
    @RequiresPermissions("school:paper:add")
    @Log(title = "试卷", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ExamPaper examPaper)
    {
        examPaperService.insertExamPaper(examPaper);
        AjaxResult ajaxResult = AjaxResult.success(examPaper.getId());
        return ajaxResult;
    }

    /**
     * 修改试卷
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ExamPaper examPaper = examPaperService.selectExamPaperById(id);
        mmap.put("examPaper", examPaper);
        return prefix + "/edit";
    }

    /**
     * 修改保存试卷
     */
    @RequiresPermissions("school:paper:edit")
    @Log(title = "试卷", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ExamPaper examPaper)
    {
        examPaperService.updateExamPaper(examPaper);
        AjaxResult ajaxResult = AjaxResult.success(examPaper.getId());
        return ajaxResult;
    }

    /**
     * 删除试卷
     */
    @RequiresPermissions("school:paper:remove")
    @Log(title = "试卷", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(examPaperService.deleteExamPaperByIds(ids));
    }


    /**
     * 答题
     */
    @GetMapping("/answer/{id}")
    public String answer(@PathVariable("id") Long id, ModelMap mmap) {

        ExamPaper examPaper = examPaperService.selectExamPaperById(id);
        mmap.put("examPaper", examPaper);
        mmap.put("user", ShiroUtils.getSysUser());
        return prefix + "/answer";
    }

    /**
     * 打印
     */
    @GetMapping("/print/{id}")
    public String print(@PathVariable("id") Long id, ModelMap mmap) {

        ExamPaper examPaper = examPaperService.selectExamPaperById(id);
        examPaper.setSubjectName(dictService.getLabel("sc_subject_type",String.valueOf(examPaper.getSubject())));
        mmap.put("examPaper", examPaper);
        mmap.put("user", ShiroUtils.getSysUser());
        return prefix + "/print";
    }

    /**
     * 打印
     */
    @GetMapping("/pdf/{id}")
    public String pdf(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {

        ExamPaper examPaper = examPaperService.selectExamPaperById(id);
        examPaper.setSubjectName(dictService.getLabel("sc_subject_type",String.valueOf(examPaper.getSubject())));
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/png");
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            createPdf(out,examPaper);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 保存试卷题目
     */
    @RequiresPermissions("school:paper:edit")
    @GetMapping("/updatePaperQuestion")
    @ResponseBody
    public AjaxResult updatePaperQuestion(Long questionId,Long paperId,Integer type)
    {

        return toAjax(examPaperService.updatePaperQuestion(questionId, paperId, type));
    }




    /**
     * 详情
     */
    @GetMapping("/detail/{id}")
    @ResponseBody
    public AjaxResult detail(@PathVariable("id") Long id) {

        ExamPaper examPaper = examPaperService.selectExamPaperById(id);
        examPaper.setSubjectName(dictService.getLabel("sc_subject_type",String.valueOf(examPaper.getSubject())));
        return AjaxResult.success(examPaper);
    }


    /**
     * 试卷答案打印
     */
    @GetMapping("/answer/print/{id}")
    public String answerPrint(@PathVariable("id") Long id, ModelMap mmap) {
        Map<Integer, Map<Long, List<ExamAnswer>>> result = examPaperService.getPaperAnswerByPaperId(id);
        mmap.put("answer", result);
        mmap.put("user", ShiroUtils.getSysUser());
        return prefix + "/answerPrint";
    }
}
